package pdf.utils;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.Image;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;

public class PdfAddCodeUtil {

    /**
     *  pdf添加图片水印
     * @param inputStream
     * @param url
     * @param handle
     * @param pdfId
     * @return
     */
    public static ByteArrayOutputStream addImgWaterMaker(InputStream inputStream,String url,String handle,String pdfId) {
        System.out.println("==========addImgWaterMaker==========start");
        ByteArrayOutputStream byteOutputStream =null;
        InputStream input = null;
        try {
            PdfReader reader = new PdfReader(inputStream);
            byteOutputStream = new ByteArrayOutputStream();
            PdfStamper stamper = new PdfStamper(reader,byteOutputStream );
            PdfGState gs1 = new PdfGState();
            // 设置透明度
            gs1.setFillOpacity(0.7f);
            byte[] bytes=null;
            Image image = null;

            // 获取PDF页数
            int num = reader.getNumberOfPages();
            PdfContentByte under;
            for (int i = 1; i <= num; i++) {
                String handleWithPageNo = handle + ".0" + i;
                String encode = URLEncoder.encode(handleWithPageNo, "UTF-8");
                bytes = CodeUtil.readInputStream(CodeUtil.bufferedImageToInputStream(CodeUtil.generateQrCode(url + "handle=" + encode + "&pdfid=" + pdfId + "&pageno=" + i)));
                image = Image.getInstance(bytes);
                PdfContentByte pdfContentByte = stamper.getOverContent(i);
                // 获得PDF最顶层
                under = stamper.getOverContent(i);
                pdfContentByte.setGState(gs1);
                // 首页
                if (i == 1){
                    String encode1 = URLEncoder.encode(handle, "UTF-8");
                    byte[] bytes1 = CodeUtil.readInputStream(CodeUtil.bufferedImageToInputStream(CodeUtil.generateQrCode(url + "handle=" + encode1 + "&pdfid=" + pdfId + "&pageno=-1")));
                    Image image1 = Image.getInstance(bytes1);
                    // 设置旋转角度
                    image1.setRotationDegrees(0);// 旋转 角度
                    // 设置等比缩放
                    under.setColorFill(BaseColor.GRAY);
                    image1.scaleToFit(100,150);
                    image1.setRotation(30);
                    image1.setAbsolutePosition(10 , 50 );
                    pdfContentByte.addImage(image1);
                }
                // 行
                for (int y = 0; y < 1; y++) {
                    // 列
                    for (int x = 0; x < 1; x++) {
                        // 设置旋转角度
                        image.setRotationDegrees(0);// 旋转 角度
                        // 设置等比缩放
                        under.setColorFill(BaseColor.GRAY);
                        image.scaleToFit(100,150);
                        image.setRotation(30);
                        image.setAbsolutePosition(500 , 50 );
                        pdfContentByte.addImage(image);
                    }
                }
            }
            stamper.close();
            reader.close();
//            input = new ByteArrayInputStream(byteOutputStream.getBytes());
            return byteOutputStream;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件增加水印异常:{}" + e.getMessage());
            return byteOutputStream;
        }
    }

    public static void main(String[] args) throws Exception {

//        waterMark("D:/1.pdf", "D:/2.pdf", "86.110.67/KZ20210186.04");
    }

    /**
     *   pdf添加文字水印
     *
     * @param inputStream
     * @param waterMarkName
     * @return
     */
    public static ByteArrayOutputStream addTextWaterMark(InputStream inputStream, String waterMarkName) {
        ByteArrayOutputStream byteOutputStream =null;
        try {
            PdfReader reader = new PdfReader(inputStream);
            byteOutputStream = new ByteArrayOutputStream();
            PdfStamper stamper = new PdfStamper(reader,byteOutputStream );
            //这里的字体设置比较关键，这个设置是支持中文的写法
            BaseFont base = BaseFont.createFont("STSong-Light",
                    "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
            int total = reader.getNumberOfPages() + 1;

            PdfContentByte under;
            Rectangle pageSizeWithRotation = null;
            for (int i = 1; i < total; i++) {
                pageSizeWithRotation = stamper.getReader().
                        getPageSizeWithRotation(i);
                //首页
                if (i == 1) {
                    // 计算水印X,Y坐标
                    float x = pageSizeWithRotation.getWidth()/10;
                    float y = pageSizeWithRotation.getHeight()/10-20;
                    // 获得PDF最顶层
                    under = stamper.getOverContent(i);
                    under.saveState();
                    // set Transparency
                    PdfGState gs = new PdfGState();
                    // 设置透明度为0.2
                    gs.setFillOpacity(1.f);
                    under.setGState(gs);
                    under.restoreState();
                    under.beginText();
                    under.setFontAndSize(base, 5);
                    under.setColorFill(BaseColor.BLACK);

//                // 水印文字成45度角倾斜
                    under.showTextAligned(Element.ALIGN_CENTER
                            , waterMarkName, x,
                            y,0);
                    // 添加水印文字
                    under.endText();
                    under.setLineWidth(1f);
                    under.stroke();
                }
                // 计算水印X,Y坐标
//                float x = pageSizeWithRotation.getWidth()/10;
                float x = 550;
                float y = pageSizeWithRotation.getHeight()/10-20;
                // 获得PDF最顶层
                under = stamper.getOverContent(i);
                under.saveState();
                // set Transparency
                PdfGState gs = new PdfGState();
                // 设置透明度为0.2
                gs.setFillOpacity(1.f);
                under.setGState(gs);
                under.restoreState();
                under.beginText();
                under.setFontAndSize(base, 5);
                under.setColorFill(BaseColor.BLACK);

//                // 水印文字成45度角倾斜
                under.showTextAligned(Element.ALIGN_CENTER
                        , waterMarkName + ".0" + i, x,
                        y,0);
                // 添加水印文字
                under.endText();
                under.setLineWidth(1f);
                under.stroke();
            }
            stamper.close();
            return byteOutputStream;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件增加水印异常:{}" + e.getMessage());
            return byteOutputStream;
        }
    }

//    public static void main(String[] args) throws Exception {
////        File file = new File("D:/ceshi2.pdf");
////        InputStream is = toImage(new FileInputStream(file),1);
////        byte[] bytes = new byte[1024];
////        int index;
////        FileOutputStream downloadFile = new FileOutputStream("D:/image1.jpg");
////        while ((index = is.read(bytes)) != -1) {
////            downloadFile.write(bytes, 0, index);
////            downloadFile.flush();
////        }
//
//
//    }

    public static void writeToLocal(String destination, InputStream input)
            throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(destination);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        input.close();
        downloadFile.close();
    }


    /**
     * 指定页数的PDF文件转换为图片
     * @param is
     * @param pageNo
     * @return
     * @throws IOException
     */
    public static InputStream toImage(ByteArrayOutputStream is,Integer pageNo) throws IOException {

        PDDocument doc =null;
        ByteArrayInputStream inputStream = null;
        try {
            //加载
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(is.toByteArray());
            BufferedInputStream bufferedInputStream = new BufferedInputStream(byteArrayInputStream);
            doc = PDDocument.load(bufferedInputStream);
            //获取全部页数
            List pages = doc.getDocumentCatalog().getAllPages();
            //指定单页转pdf
            if (pageNo != null) {
                //接收页面
                PDPage page = (PDPage) pages.get(pageNo);
                //定义图片操作对象来设置图片
                BufferedImage image = page.convertToImage();
//                PDFRenderer pdfRenderer = new PDFRenderer(doc);
//                BufferedImage image = pdfRenderer.renderImageWithDPI(pageNo,50);
                //定义迭代器对象存储
                Iterator iter = ImageIO.getImageWritersBySuffix("jpg");
                //图片写入器对象写入图片
                ImageWriter writer = (ImageWriter) iter.next();
                //创建文件输出流对象
//                FileOutputStream out = new FileOutputStream(new File("D:/image1.jpg"));
                ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
                //ImageIO去实现ImageOutputStream获取当前图片
                ImageOutputStream outImage = ImageIO.createImageOutputStream(byteOutputStream);
                writer.setOutput(outImage);
                writer.write(new IIOImage(image, null, null));
                inputStream = new ByteArrayInputStream(byteOutputStream.toByteArray());
            }
            //操作后的页数
            System.out.println(pageNo);
            System.out.println("over");
            return inputStream;
        } catch (Exception e) {
            e.printStackTrace();
            return inputStream;
        } finally{
            if( doc != null ){
                //关闭文档
                doc.close();
            }
        }
    }


    /**
     * outputstream获取总页数
     * @param os
     * @return
     */
    public static Integer getNumberOfPages(ByteArrayOutputStream os) {
        try {
//            ByteOutputStream bos = (ByteOutputStream) is;
//            PDDocument pdDocument = PDDocument.load(is);
//            return pdDocument.getNumberOfPages();
            PdfReader reader = new PdfReader(os.toByteArray());
            int numberOfPages = reader.getNumberOfPages();
            return numberOfPages;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * inputstream 获取总页数
     * @param is
     * @return
     */
    public static Integer getNumberOfPages(InputStream is) {
        try {
//            ByteOutputStream bos = (ByteOutputStream) is;
//            PDDocument pdDocument = PDDocument.load(is);
//            return pdDocument.getNumberOfPages();
            PdfReader reader = new PdfReader(is);
            int numberOfPages = reader.getNumberOfPages();
            return numberOfPages;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }


}
